<?php
namespace IFeng\Process;
require_once 'IFeng/Process/Process.php';
require_once 'IFeng/Process/ChildProcess.php';
class MainProcess extends Process {
	/**
	 * fork and run Pp/Runnable::run() in child process
	 * @throws FailToForkException
	 * @param Runnable $runnable
	 * @return ChildProcess
	 */
	public function fork(Runnable $runnable) {
		if (!$this->isCurrent()) {
			require_once 'IFeng/Process/FailToForkException.php';
			throw new FailToForkException('the instance does not represent current main process.');
		}
		$pid = \pcntl_fork();
		if ($pid == -1) {
			require_once 'IFeng/Process/FailToForkException.php';
			throw new FailToForkException('fail to folk.');
		}
		
		if ($pid == 0) {
			$code = $runnable->run();
			if (!\is_int($code)) {
				$code = 1;
			} else if (\is_null($code)) {
				$code = 0;
			}
			exit($code);
		}
		
		return new ChildProcess($pid); 	
	}
}